package com.cn.namesrv;

import com.cn.common.BrokerAppStore;
import com.cn.common.BrokerCluster;
import com.cn.common.BrokerEntity;
import com.cn.common.BrokersUrlStore;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 服务提供端 心跳处理
 */
public class NameSrvConnectManageHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state.equals(IdleState.ALL_IDLE)) {
                System.out.println("检测到与客户端失去连接了，关闭通道。");
                NameRemoveBroker.close(ctx);
            }
        }
        ctx.fireUserEventTriggered(evt);
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
//        ctx.close();
        NameRemoveBroker.close(ctx);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
//        ctx.close();
        NameRemoveBroker.close(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ctx.close();
        NameRemoveBroker.close(ctx);
    }
}
